home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1174 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Strcat Doesn't work for this?
  5. Date: 11 Jan 1996 15:22:10 -0800
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4d4632$mj0@crl.crl.com>
  8. References: <Pine.SOL.3.91.960111151925.25068C-100000@lore.cs.purdue.edu>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. ** Craig Cook ** <cookca@cs.purdue.edu> writes:
  12.  
  13. >Here is my excerpt of code in question:
  14.  
  15. >Putword(int w, char *imageChar)
  16. >{
  17. >        w = (w & 0xff);
  18. >        strcat( imageChar, (const char *)w );
  19. >}
  20.  
  21. >Why does it core dump?  It should work right?
  22.  
  23. Actually, no it shouldn't. Strcat is expecting two pointers to character,
  24. and you are passing it a pointer and a single byte that has been cast to 
  25. a pointer. In actual fact, your second parameter has now become a pointer 
  26. with a value ranging from 0-255.
  27.  
  28. Remember, this second parameter should be a string. That is, a sequence 
  29. of bytes terminated by a NULL. Assuming you're on a little-endian machine 
  30. (which you appear to be doing -- it's /far/ from guaranteed!), if you 
  31. change the call to strcat to look like: strcat( imageChar, (const char *)&w);
  32. then this code should append the low-order byte of w to the imageChar string.
  33.  
  34. I think most people would consider this to be poorly-written, however. It 
  35. invokes hardware-dependent behavior as well as only writing one byte, not 
  36. a word on the off chance it DOES work. If you have to perform this 
  37. operation, memcpy is probably a better way to do it -- or simply do the 
  38. appropriate mask-and-shift operations to copy to the appropriate position 
  39. in imageChar.
  40.  
  41.